<template>
  <div>
    <div style="
                background: #fff;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: #666;
            ">
      <div style="width: 100%">
        <span style="
                        font-size: 20px;
                        margin: 30px 40px;
                        display: inline-block;
                        color: #000;
                    ">
          <i class="el-icon-document"></i>
          活动基本信息
        </span>
        <el-button size="mini" @click="goback()" type="primary"
          style="margin-left: 1000px; margin-bottom: 20px">返回</el-button>
        <el-form :disabled="this.$route.params.flag3" :model="ruleForm" :rules="rules" ref="ruleForm"
          label-width="100px" class="demo-ruleForm">
          <el-row :gutter="20">
            <el-col :span="6" :push="1">
              <div class="grid-content bg-purple">
                <el-form-item label="活动名称" prop="activityName">
                  <el-input v-model="ruleForm.activityName" type="text" maxlength="15" show-word-limit></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="11" :push="1">
              <div class="grid-content bg-purple">
                <el-form-item label="活动有效期" required>
                  <el-col :span="10">
                    <el-form-item prop="date1">
                      <el-date-picker placeholder="选择日期" v-model="ruleForm.date1" style="width: 100%" type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col class="line" :span="2">-</el-col>
                  <el-col :span="10">
                    <el-form-item prop="date2">
                      <el-date-picker placeholder="选择日期" v-model="ruleForm.date2" style="width: 100%" type="datetime"
                        value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>

            <el-col :span="7" :push="0">
              <div class="grid-content bg-purple">
                <el-form-item label="兑奖截至日期" required label-width="120px">
                  <el-col :span="10">
                    <el-form-item prop="cashDeadline">
                      <el-date-picker placeholder="选择日期" v-model="ruleForm.cashDeadline" style="width: 210px"
                        type="datetime" value-format="yyyy-MM-dd HH:mm:ss" @change="
                          (data) => {
                            ruleForm.cashDeadline = todataformat(
                              data
                            );
                          }
                        "></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="5" :push="1">
              <div class="grid-content bg-purple">
                <el-form-item label="每次消耗" prop="score">
                  <el-input v-model.number="ruleForm.score" type="number" min="0" class="input_edit">
                    <template slot="append">酒币</template>
                  </el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12" :push="1">
              <div class="grid-content bg-purple">
                <el-form-item label="活动状态" prop="status">
                  <el-select v-model="ruleForm.status" placeholder="请选择活动状态">
                    <el-option label="已发布" value="1"></el-option>
                    <el-option label="未发布" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="15" :push="1">
              <div class="grid-content bg-purple">
                <el-form-item label="活动规则" prop="activityDesc">
                  <el-input type="textarea" v-model="ruleForm.activityDesc" :rows="4"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <div style="
                background: #fff;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: #666;
            ">
      <div style="width: 100%">
        <span style="
                        font-size: 20px;
                        margin: 30px 40px;
                        display: inline-block;
                        color: #000;
                    ">
          <i class="el-icon-document"></i>
          赠品配置
        </span>

        <el-table :data="tableData" style="width: 100%" border :header-cell-style="{
          background: '#eef1f6',
          color: '#606266',
        }">
          <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>

          <el-table-column prop="prizeLevelName" label="赠品等级名称" width="130">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prizeLevelName" :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="giftCode" label="赠品编码"></el-table-column>
          <el-table-column prop="giftName" label="赠品名称"></el-table-column>
          <el-table-column prop="giftPic" label="赠品图片">
            <template slot-scope="scope">
              <img :src="scope.row.giftPic" v-if="
                scope.row.giftPic != '' &&
                scope.row.giftPic != null
              " width="70" height="50" />
            </template>
          </el-table-column>
          <el-table-column prop="giftDesc" label="赠品描述" show-overflow-tooltip></el-table-column>
          <el-table-column prop="giftType" label="赠品类型">
            <template slot-scope="scope">
              <span v-if="scope.row.giftType === 1">实物赠品</span>
              <span v-if="scope.row.giftType === 2">虚拟赠品</span>
            </template>
          </el-table-column>
          <el-table-column prop="deliveryType" label="配送方式" width="240" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.deliveryType" v-if="scope.row.giftType === 1" :disabled="flag3"
                size="mini">
                <el-radio-button label="1">专卖店配送</el-radio-button>
                <el-radio-button label="2">五粮液总部配送</el-radio-button>
              </el-radio-group>
              <span v-if="scope.row.giftType === 2">——————</span>
            </template>
          </el-table-column>
          <el-table-column prop="validType" label="有效期类型" width="180" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.validType" v-if="
                scope.row.giftType === 2 &&
                scope.row.giftStyle !== 3 &&
                scope.row.giftStyle !== 5
              " :disabled="flag3">
                <el-radio-button label="1">天数</el-radio-button>
                <el-radio-button label="2">日期</el-radio-button>
              </el-radio-group>
              <span v-else>——————</span>
            </template>
          </el-table-column>
          <el-table-column prop="giftStyle" label="类型" v-if="false"></el-table-column>
          <el-table-column prop="validDate" label="有效天数" align="center" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.validDate" @blur="numberBlur($event, '有效天数')" v-if="
                scope.row.giftType === 2 &&
                scope.row.validType == 1 &&
                scope.row.giftStyle !== 3 &&
                scope.row.giftStyle !== 5
              " style="
                                    width: 100px;
                                    text-align: right;
                                    text-align-last: right;
                                " placeholder :disabled="flag3"></el-input>
              <el-date-picker v-model="scope.row.validCreateDate" v-if="
                scope.row.giftType === 2 &&
                scope.row.validType == 2 &&
                scope.row.giftStyle !== 3 &&
                scope.row.giftStyle !== 5
              " type="date" value-format="yyyy-MM-dd" style="width: 140px" placeholder="请选择生效时间"
                :disabled="flag3"></el-date-picker>
              <el-date-picker v-model="scope.row.validEndDate" v-if="
                scope.row.giftType === 2 &&
                scope.row.validType == 2 &&
                scope.row.giftStyle !== 3 &&
                scope.row.giftStyle !== 5
              " type="date" value-format="yyyy-MM-dd" style="width: 140px" placeholder="请选择失效时间"
                :disabled="flag3"></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="prizeQuantity" label="赠品数量">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.prizeQuantity"
                :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="giftCount" label="赠送数量">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.giftCount"
                :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="winningQuantityDay" label="当日中奖数量">
          </el-table-column>
          <el-table-column prop="prizeQuantityDay" label="每日中奖上限">
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.prizeQuantityDay"
                :disabled="flag3" v-on:input="compare(scope.row, scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="winningRate" label="中奖概率（%）" required>
            <template slot-scope="scope">
              <el-input :maxlength="8" oninput="value=value.replace(/[^0-9.]/g,'')" v-model="scope.row.winningRate"
                @blur="blur($event, '中奖概率')" :disabled="flag3"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="200px" v-if="!this.flag3">
            <template slot-scope="scope">
              <el-button size="mini" @click="checkjiang(scope.row, scope.$index)" type="text">选择赠品</el-button>
              <el-button size="mini" @click="delprice(scope.$index)" type="text">删除奖项</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item>
            <el-button type="primary" @click="add()" size="mini" icon="el-icon-edit" v-if="!this.flag3">增加奖项</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div style="
                background: #fff;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                color: #666;
            ">
      <div style="width: 100%">
        <span style="
                        font-size: 20px;
                        margin: 30px 40px;
                        display: inline-block;
                        color: #000;
                    ">
          <i class="el-icon-document"></i>
          会员抽奖免费次数
        </span>
        <el-row :gutter="20">
          <el-col :span="15" :push="1">
            <div class="grid-content bg-purple" style="display: flex; margin: 10px 0">
              <div style="display: flex; align-items: center; font-size: 14px;">
                <span>五粮液会员每天</span>
                <span style="margin: 0 10px">
                  <el-input v-model="freeNum" placeholder="请输入次数" oninput="value=value.replace(/[^0-9]/g,'')"
                    :disabled="flag3"></el-input>
                </span>
                <span>次</span>
              </div>
            </div>
            <!-- <div class="grid-content bg-purple" style="display: flex; margin: 10px 0" v-for="(send, index) in options"
              :key="index">
              <div style="display: flex; align-items: center; font-size: 14px;">
                <span>{{ send.gradelevelName }}</span>
                <span>每天</span>
                <span style="margin: 0 10px">
                  <el-input v-model="data[index]" placeholder="请输入次数" oninput="value=value.replace(/[^0-9]/g,'')"
                    :disabled="flag3"></el-input>
                </span>
                <span>次,</span>
              </div>
              <div style="display: flex; align-items: center; font-size: 14px;">
                <span style="margin: 0 10px">对所有赠品中奖概率提升</span>

                <span style="margin: 0 10px">
                  <el-input v-model="dataone[index]" placeholder="请输入提升概率" :disabled="flag3"></el-input>
                </span>
                <span>%</span>
              </div>
            </div> -->
          </el-col>
        </el-row>
      </div>
    </div>
    <el-button size="mini" @click="postsure()" type="primary" style="margin-left: 600px"
      v-if="!this.$route.params.flag3">确定</el-button>
    <el-button size="mini" @click="delsure()" type="primary" v-if="!this.$route.params.flag3">取消</el-button>
    <el-dialog title="赠品列表" :visible.sync="dialogVisible" width="80%">
      <el-table :data="tableDataone" style="width: 100%; max-height: 500px; overflow: auto;" @select="handleRow"
        ref="tables" @selection-change="handleSelectionChange" border
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="giftCode" label="赠品编码"></el-table-column>
        <el-table-column prop="giftName" label="赠品名称"></el-table-column>
        <el-table-column prop="giftPic" label="赠品图片">
          <template slot-scope="scope">
            <img :src="scope.row.giftPic" v-if="
              scope.row.giftPic != '' &&
              scope.row.giftPic != null
            " width="70" height="50" />
          </template>
        </el-table-column>
        <el-table-column prop="giftDesc" label="赠品描述"></el-table-column>
        <el-table-column prop="giftType" label="赠品类型">
          <template slot-scope="scope">
            <span v-if="scope.row.giftType === 1">实物赠品</span>
            <span v-if="scope.row.giftType === 2">虚拟赠品</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sure()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getmemberrule } from "@/api/membergrade";
import { queryPrize, createActivityConfig } from "@/api/lotteryActivityset";
import { qryGiftBank } from "@/api/giftbank";
export default {
  data() {
    return {
      keepAlive: true,
      data: [],
      dataone: [],
      options: [],

      ruleForm: {
        uuid: "",
        activityName: "",
        status: "0",
        date1: "",
        date2: "",
        activityDesc: "",
        score: "",
        cashDeadline: ""
      },

      formInline: {
        gradelevelName: "",
        gradelevelCode: ""
      },
      flag: false,
      flag3: false,
      selectone: [],
      dialogVisible: false,
      tableData: [],
      tableDataone: [],
      tableDatatwo: [],
      glevel: [],
      rules: {
        activityName: [
          { required: true, message: "请输入活动名称", trigger: "blur" }
        ],
        score: [
          { required: true, message: "请输入每次消耗酒币", trigger: "blur" }
        ],
        activityDesc: [
          { required: true, message: "请输入活动规则", trigger: "blur" }
        ],
        cashDeadline: [
          { required: true, message: "请输入兑奖截止日期", trigger: "blur" }
        ],
        date1: [
          {
            type: "string",
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        date2: [
          {
            type: "string",
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ]
      },
      freeNum: 0
    };
  },
  mounted() {
    this._getmemberinfo();
    this.setprice();
    this.flag3 = this.$route.params.flag3;
    if (this.$route.params.edit) {
      this.flag = true;
      this.ruleForm.uuid = this.$route.params.edit.uuid;
      this.ruleForm.activityName = this.$route.params.edit.activityName;
      this.ruleForm.status = String(this.$route.params.edit.status);
      this.ruleForm.date1 = this.$route.params.edit.activityBeginTime;
      this.ruleForm.date2 = this.$route.params.edit.activityEndTime;
      this.ruleForm.activityDesc = this.$route.params.edit.activityDesc;
      this.ruleForm.cashDeadline = this.$route.params.edit.cashDeadline;
      this.ruleForm.score = this.$route.params.edit.score;
      this.tableData = this.$route.params.edit.promotionActivityPrizeConfigDTOList;
      // this.tableData.map(item => {
      //     if(item["uuid"] != undefined){
      //       delete item["uuid"];
      //     }
      //   });
      this.glevel = this.$route.params.edit.promotionActivityMemberConfigDTOList;
    } else {
      this.flag = false;
    }
  },
  methods: {
    numberBlur(e, name) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
    },
    enterinput(v, index) {
      console.log(this.data, "88");
      console.log(this.dataone, "88999");
      console.log(v, index, "opo9");
    },
    enterinputone(v, index) {
      console.log(v, index, "opo9");
    },
    goback() {
      this.$router.go("-1");
    },
    handleRow(selection, row) {
      // 先清除所有选中的
      this.$refs.tables.clearSelection();
      // 当前的点击实现勾选
      this.$refs.tables.toggleRowSelection(row);
    },

    _getmemberinfo() {
      let data = {
        size: 10,
        current: 1,
        condition: {},
        ascs: [],
        descs: []
      };
      getmemberrule(data).then(res => {
        this.options = res.records;
        if (this.$route.params.edit) {
          this.freeNum = this.glevel[0].dayTimes;
          this.glevel.forEach((item, i) => {
            let index = this.options.findIndex((ff, i) => { return ff.uuid === item.memberLevelId });
            this.data[index] = item.dayTimes;
            // this.dataone[index] = item.addWinningRate;
          }
          );
        } else {
          this.freeNum = 0;
          this.options.forEach((item, i) => {
            this.data.push(this.freeNum);
            // this.dataone.push("0");
          });
        }
      });
    },
    setprice() {
      this.tableData.push(
        { prizeLevel: "1", prizeLevelName: "一等奖", giftCode: "" },
        { prizeLevel: "2", prizeLevelName: "二等奖", giftCode: "" },
        { prizeLevel: "3", prizeLevelName: "三等奖", giftCode: "" },
        { prizeLevel: "4", prizeLevelName: "四等奖", giftCode: "" },
        { prizeLevel: "5", prizeLevelName: "五等奖", giftCode: "" }
      );
    },

    checkjiang(v, index) {
      this.level = index;
      this.dialogVisible = true;
      let data = {
        size: 99,
        current: 1,
        condition: {
          giftName: "",
          giftCode: "",
          giftType: "",
          ActivityType: 0
        },
        ascs: [],
        descs: []
      };
      qryGiftBank(data)
        .then(res => {
          res.records.forEach((item, i) => {
            item.validType = item.giftType == 1 ? "2" : "1";
            // this.$set(item,'validType',item.giftType == 1 ? "2" : "1");
          });
          this.tableDataone = res.records;
          if (this.tableDataone.length > 0) {
            for (var i in this.tableData) {

              if (this.tableData[i].giftCode != null && this.tableData[i].giftCode != '' && this.tableData[i].giftCode.length != 0) {
                this.removeByValue(this.tableDataone, "giftCode", this.tableData[i].giftCode);
              }
            }
          }
        })
      // .then(() => {
      // for (let i = 0; i < this.tableDataone.length; i++) {
      // if (this.tableDataone[i].giftCode == v.giftCode) {
      //   this.$refs.tables.toggleRowSelection(this.tableDataone[i], true);
      // }
      // }
      // }
    },
    checkboxT(row, rowIndex) {
      // if(rowIndex==4){
      if (true) {
        //  if(row.giftCode =='1'){
        return false;//禁用
      } else {
        return true;//不禁用
      }
    },
    blur(e, name) {
      if (e.target.value > 100) {
        this.$message({
          message: name + "请正确输入中奖概率且不大于100",
          type: "warning"
        });
        return e.target.value = '';
      }
      // let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      let a = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      let flag = a.test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请正确输入中奖概率且不大于100",
          type: "warning"
        });
        e.target.value = '';
      }
    },
    sure() {
      this.dialogVisible = !this.dialogVisible;
      this.tableData.forEach((item, i) => {
        if (this.level == i) {
          this.selectData[0].prizeLevelName = this.tableData[i].prizeLevelName;
          this.selectData[0].prizeLevel = this.tableData[i].prizeLevel;
          this.selectData[0]["prizeId"] = this.selectData[0]["uuid"];
          delete this.selectData[0]["uuid"];
          let returnedTarget = Object.assign({}, this.tableData[i], this.selectData[0]);
          this.$set(returnedTarget, 'prizeQuantity', 1)
          this.$set(returnedTarget, 'giftCount', 1)
          this.$set(returnedTarget, 'prizeQuantityDay', 1)
          this.$set(returnedTarget, 'winningRate', '')
          if (this.selectData[0].giftType == 2) {
            this.$set(returnedTarget, 'deliveryType', '1')
          }
          this.tableData[i] = returnedTarget;
          this.tableDatatwo = this.tableData;
        }
      });
      this.tableData = [];
      this.tableDatatwo.forEach((item, i) => {
        this.tableData.push(item);
      });
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    add() {
      this.tableData.push({ prizeLevel: this.tableData.length + 1 + "" });
    },
    delprice(index) {
      this.tableData.splice(index, 1);
    },
    // 几等奖的数字转换文字
    changePrizeLevel(index) {
      const numMap = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];
      return `${numMap[index]}等奖`;
    },
    // 对数组中相应的字段进行验证
    hasEmptyFields(array, fields) {
      fields = [
        'giftPic', 'giftName', 'prizeQuantity', 'giftCount', 'prizeQuantityDay', 'winningRate'
      ];
      const greaterThanZero = [
        'prizeQuantity', 'giftCount', 'prizeQuantityDay', 'winningRate'
      ];

      // 边界判断
      if (!Array.isArray(array)) return false;
      if (!Array.isArray(fields)) return false;

      // 边界判断
      if (!Array.isArray(array) || array.length === 0) {
        return false; // 没有数据，视为无错误
      }

      // 使用 for...of，可以中途 return 错误信息
      for (let i = 0; i < array.length; i++) {
        const item = array[i];

        // 确保是对象
        if (typeof item !== 'object' || item === null) {
          return `第 ${i + 1} 项数据格式错误，必须是对象`;
        }

        // 1. 检查必填字段是否为空
        for (const field of fields) {
          const value = item[field];

          if (greaterThanZero.includes(field)) {
            if (value == null || value === '' || value <= 0) {
              return `${this.changePrizeLevel(i)} 填写的奖品信息有误,请检查`;
            }
          } else {
            if (value == null || value === '') {
              return `${this.changePrizeLevel(i)} 填写的奖品信息有误,请检查`;
            }
          }
        }

        // 2. 业务逻辑校验：单次赠送数量不能大于总奖品数量
        if (item.prizeQuantity < item.giftCount) {
          return `${this.changePrizeLevel(i)} 的单次赠送数量不能大于奖品数量`;
        }
      }

      // 全部通过
      return false;
    },
    postsure() {
      if (this.ruleForm.activityName == "" || this.ruleForm.activityName == null) {
        this.$message.error("请输入活动名称");
        return;
      }
      if (this.ruleForm.date1 == "" || this.ruleForm.date1 == null) {
        this.$message.error("请输入开始时间");
        return;
      }
      if (this.ruleForm.date2 == "" || this.ruleForm.date2 == null) {
        this.$message.error("请输入结束时间");
        return;
      }
      if (this.ruleForm.cashDeadline == "" || this.ruleForm.cashDeadline == null) {
        this.$message.error("请输入兑奖截止日期");
        return;
      }
      if (this.ruleForm.date1 > this.ruleForm.date2) {
        this.$message.error("结束时间不能早于开始时间");
        return;
      }
      if (this.ruleForm.cashDeadline < this.ruleForm.date1) {
        this.$message.error("兑奖截止日期不能早于开始时间");
        return;
      }

      // if (this.ruleForm.score == "" || this.ruleForm.score == null) {
      //   this.$message.error("请输入消耗值");
      //   return;
      // }
      if (this.ruleForm.activityDesc == "" || this.ruleForm.activityDesc == null) {
        this.$message.error("请输入活动描述");
        return;
      }

      this.options.forEach((item, i) => {
        if (this.$route.params.edit) {
          this.glevel.forEach((item, i) => {
            let index = this.options.findIndex((ff, i) => { return ff.uuid === item.memberLevelId });
            this.glevel[index].dayTimes = this.freeNum;
            // this.glevel[i].addWinningRate = this.dataone[index];
          });
        } else {
          this.glevel.push({
            uuid: "",
            memberLevelId: this.options[i].uuid,
            activityId: "",
            dayTimes: this.freeNum,
            // addWinningRate: this.dataone[i],
            status: 1
          });
        }
      });
      this.selectone = [];
      this.tableData.forEach((item, i) => {
        item.prizeLevel = i + 1;
        if (this.tableData[i].giftCode) {
          this.selectone.push(this.tableData[i]);
        }
      });
      let r = new RegExp("^[1-9][0-9]*$");
      for (var i in this.selectone) {
        var flag1 = true;
        var flag2 = true;
        var flag3 = true;
        var prizeQuantity = this.selectone[i].prizeQuantity;
        var prizeQuantityDay = this.selectone[i].prizeQuantityDay;
        // var winningRate = this.selectone[i].winningRate;
        if (prizeQuantity == null || prizeQuantity == "" || !r.test(prizeQuantity)) {
          flag1 = false;
          break;
        }
        if (prizeQuantityDay == null || prizeQuantityDay == "" || !r.test(prizeQuantityDay)) {
          flag2 = false;
          break;
        }
        if (prizeQuantityDay == null || prizeQuantityDay == "" || !r.test(prizeQuantityDay)) {
          flag2 = false;
          break;
        }
        // if (winningRate == null || winningRate == "") {
        //   flag3 = false;
        //   break;
        // }
      }
      if (!flag1) {
        this.$message({ message: "请正确输入赠品数量", type: "warning" }); return;
      }
      if (!flag2) {
        this.$message({ message: "请正确输入每日中奖上限", type: "warning" }); return;
      }
      // if (!flag3) {
      //   this.$message({ message: "请正确输入中奖概率", type: "warning" }); return;
      // }
      if (false) {
        let newData = [];
        let obj = {};
        this.selectone.map(item => {
          obj = item;
          if (item["uuid"] != undefined) {
            // obj["prizeId"] = item["uuid"];
            // delete obj["uuid"];
            newData.push(obj);
          }
        });
      }
      let data = {
        uuid: this.ruleForm.uuid,
        activityName: this.ruleForm.activityName,
        activityBeginTime: this.ruleForm.date1,
        activityEndTime: this.ruleForm.date2,
        cashDeadline: this.ruleForm.cashDeadline,
        score: this.ruleForm.score,
        status: this.ruleForm.status,
        activityDesc: this.ruleForm.activityDesc,
        promotionActivityPrizeConfigDTOList: this.selectone,
        promotionActivityMemberConfigDTOList: this.glevel
      };

      this.keepAlive = false;

      // 验证奖品信息内容
      const validResult = this.hasEmptyFields(data.promotionActivityPrizeConfigDTOList);

      if (validResult) {
        this.$message.error(typeof validResult === 'string' ? validResult : '填写的奖品信息有误,请检查');
        return
      }

      // console.info(data);
      if (this.$route.params.edit) {
        createActivityConfig(data).then(res => {
          this.tableDataone = res.records;
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.glevel = [];
            this.delsure();
            // this.$router.push("lotteryActivitysetxinedit");
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error"
            });
            this.selectone = [];
          }
        });
      } else {
        createActivityConfig(data).then(res => {
          this.tableDataone = res.records;
          if (res.code == "1") {
            this.$message({
              showClose: true,
              message: "保存成功",
              type: "success"
            });
            this.glevel = [];
            this.delsure();
            // this.$router.push("lotteryActivitysetxinedit");
          } else {
            this.$message({
              showClose: true,
              message: res.message,
              type: "error"
            });
            this.selectone = [];
          }
        });
      }
    },

    delsure() {
      // this.$router.push("lotteryActivitysetxinedit");
      this.$router.back();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    compare(value, index) {
      var number = value.prizeQuantity;
      var val = value.prizeQuantityDay;
      if (number === null || number === undefined || number === "") {
        this.$message({ showClose: true, message: "请输入赠品数", type: "info" });
        this.tableData[index].prizeQuantityDay = ''
        return false;
      }
      if (val === null || val === undefined || val === "") {
        this.$message({ showClose: true, message: "请输入每日中奖数", type: "info" });
        this.tableData[index].prizeQuantityDay = ''
        return false;
      } else {
        if (Number(val) > Number(number)) {
          this.$message({ showClose: true, message: "每日中奖数不能高于赠品数", type: "info" });
          this.tableData[index].prizeQuantityDay = number
          return false;
        }
      }
    },
    compare2(e, name, val) {
      if (e.target.value == "") {
        return;
      }
      let flag = new RegExp("^[1-9][0-9]*$").test(e.target.value);
      if (!flag) {
        this.$message({
          message: name + "请输入正整数",
          type: "warning"
        });
        e.target.value = "";
      }
      if (val === null || val === undefined || val === "") {
        this.$message({ showClose: true, message: "请输入每日中奖数", type: "info" });
        return e.target.value = "";
      } else {
        if (Number(e.target.value) > Number(val)) {
          this.$message({ showClose: true, message: "每日中奖数不能高于赠品数", type: "info" });
          return e.target.value = val;
        }
      }
    },
    // 数组，属性，属性值
    removeByValue: function (arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    todataformat(val, type) {
      // 值，符号
      if (val === null || val === undefined || val === "") {
        return "";
      } else {
        if (this.ruleForm.date1 == "" || this.ruleForm.date1 == null) {
          this.$message.error("请输入开始时间");
          return "";
        }
        if (this.ruleForm.date2 == "" || this.ruleForm.date2 == null) {
          this.$message.error("请输入结束时间");
          return "";
        }
        if (val < this.ruleForm.date1) {
          this.$message.error("兑奖截止日期不能早于开始时间");
          return "";
        }
        return val;
      }
    },
  },
  beforeRouteLeave(to, from, next) {
    // 设置下一个路由的 meta
    to.meta.keepAlive = this.keepAlive; // C 跳转到 A 时让 A 不缓存，即刷新
    next();
  },
};
</script>
